<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>IndexJWT</title>
  </head>
  <body>
    <button id="login">登录</button>
    <button id="order">查询订单</button>
    <button id="site">查询地址</button>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.9.0/axios.min.js"></script>
    <script>
      const loginEle = document.getElementById('login')
      const orderEle = document.getElementById('order')
      const siteEle = document.getElementById('site')

      // 设置axios请求实例
      const axiosInstance = axios.create({
        baseURL: 'http://127.0.0.1:4169',
        timeout: 10000,
      })

      // 添加请求拦截器
      axiosInstance.interceptors.request.use(
        function (config) {
          let token = localStorage.getItem('token')
          if (token) {
            // 设置请求头
            config.headers.authorization = token
          }
          return config
        },
        function (error) {
          return Promise.reject(error)
        }
      )

      // 添加响应拦截器
      axiosInstance.interceptors.response.use(
        function (response) {
          return response.data
        },
        async function (error) {
          if (error.status === 401) {
            // 先从本地存储拿出refreshToken
            let refreshToken = localStorage.getItem('refreshToken')

            try {
              // 请求刷新接口
              let { data } = await axios.post(
                'http://127.0.0.1:4169/refreshToken',
                {
                  refreshToken,
                }
              )

              // token重新持久化
              localStorage.setItem('token', data.data.token)
              // 重新发起请求
              axiosInstance(error.config)
              console.log('刷新token成功')
            } catch (error) {
              console.log('刷新token失败了,重新登录')
              localStorage.clear()
            }
          }
          return Promise.reject(error)
        }
      )

      // 发送请求
      loginEle.addEventListener('click', async () => {
        let data = await axiosInstance.post('/login', {
          username: 'erqiao',
          password: '20040228',
        })
        if (data.code === 20000) {
          // 将token持久化
          localStorage.setItem('token', data.data.token)
          localStorage.setItem('refreshToken', data.data.refreshToken)
        }
        alert(data.message)
      })

      // 查询订单
      orderEle.addEventListener('click', async () => {
        let token = localStorage.getItem('token')
        let data = await axiosInstance.get('/api/order')
        console.log(data)
      })

      // 查询地址
      siteEle.addEventListener('click', async () => {
        let token = localStorage.getItem('token')
        let data = await axiosInstance.get('/api/site')
        console.log(data)
      })
    </script>
  </body>
</html>
